<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
            <!-- <el-form-item>
              <el-button type="primary" size="mini" @click="showAddDialogForm">新增</el-button>
            </el-form-item> -->
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" size="mini" @click="search">刷新</el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button type="primary" size="mini" @click="exportExcel">Excel导出</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="handleExcelImp">Excel导入</el-button>
            </el-form-item> -->
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="打包项目名称"
        min-width="120">
      </el-table-column>

      <el-table-column
        prop="carName"
        label="车型类别"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="productTypeName1"
        label="一级分类"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="productTypeName2"
        label="二级分类"
        min-width="120">
      </el-table-column>


      <el-table-column
        prop="orgPriceCost"
        label="成本打包费用"
        min-width="110">
        <template scope="scope" >
          {{ToFixed(scope.row.orgPriceCost)}}
        </template>
      </el-table-column>

      <el-table-column
        prop="note"
        label="备注"
        min-width="200">
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
        min-width="170">
        <template slot-scope="scope">

          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>

          <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <!-- <el-form-item label="套餐名称" label-width="100px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="车型" label-width="100px" prop="carTypeId">
          <el-select v-model="editForm.carTypeId" :disabled="editForm.id==0?false:true"  placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="item in carTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="产品类型" label-width="100px" prop="testProductTypeId">
          <el-cascader  style="width: 100%;"
              v-model="editForm.testProductTypeId"
              :disabled="editForm.id==0?false:true"
              :options="testProductTypeList"
              :props="{ expandTrigger: 'click', value: 'id', label: 'name' }"
              ></el-cascader>
        </el-form-item>
        <el-form-item label="序号" label-width="100px" prop="serialNumber">
          <el-input v-model="editForm.serialNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="检测项目" label-width="100px" prop="itemName">
          <el-input v-model="editForm.itemName" autocomplete="off"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="检测项目" label-width="100px" prop="testItemIdListTemp">
          <el-cascader style="width: 100%;"
              v-model="editForm.testItemIdListTemp"
              :options="testItemList"
              :props="{ multiple: true,expandTrigger: 'click', value: 'id', label: 'itemName' }"
              ></el-cascader>
        </el-form-item> -->

        <el-form-item label="成本打包费用" label-width="120px" prop="orgPriceCost">
          <el-input v-model="editForm.orgPriceCost" type="number" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="场地成本费用" label-width="120px" prop="sitePriceCost">
          <el-input v-model="editForm.sitePriceCost" type="number" autocomplete="off"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.note" autocomplete="off"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="excel导入" :visible.sync="excelImp.dialogVisible" width="60%" :close-on-click-modal="false">
          <el-form>
            <el-row>
              <el-col :span="24">
                <a :href="'https://cdn.ybh.gengduoke.com/sitePrice-template.xlsx'" target="_blank">点击下载导入模板</a>
              </el-col>
            </el-row>
            <el-row style="margin-top: 20px;">
              <el-col :span="24">
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  name="file"
                  :action="excelImp.action"
                  :multiple="false"
                  :limit="1"
                  accept=".xls,.xlsx"
                  :file-list="excelImp.fileList"
                  :auto-upload="false"
                  :on-success="onUploadSuccess"
                  :on-error="onUploadError">
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <!--              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
                  <div slot="tip" class="el-upload__tip">只能上传xls/xlsx</div>
                </el-upload>
              </el-col>
            </el-row>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="excelImp.dialogVisible = false">关 闭</el-button>
            <el-button type="primary" @click.native.prevent="submitUpload" :loading="excelImp.loading">立即导入</el-button>
          </div>
        </el-dialog>



  </div>
</template>




<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
// import {getTestGroupList, addTestGroup, updateTestGroup, deleteTestGroup} from "../../../api/test_group.js"
import {getAllCarTypeList} from "../../../api/car_type.js"
import {getAllTestProductTypeList} from "../../../api/test_product_type.js"
import {getTestItemList,addTestItem,updateTestItem,deleteTestItem} from "../../../api/test_item.js"
import {getTestSitePriceList, updateTestSitePrice,getTestSiteList} from '../../../api/test_site_price.js'
import {getTestOrgPriceCostList, updateTestOrgPriceCost} from '../../../api/test_org_price_manage.js'
import {getToken} from "../../../common/utils/auth";
import axios from "axios";

export default {
  name: "testCarEnterprisePriceManage",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      siteName: '',
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      editForm: {
        id: 0,
        itemName:'',
        sitemItemId:',',
        serialNumber:'',
        carTypeId: '',
        testProductTypeId:'',
        testItemIdListTemp: [],
        testItemIdList: [],
        testItemIdsList: [],
        sitePrice:'',
        sitePriceCost:'',
        note: '', // 备注
        productTypeId1:'',
        productTypeId2:'',
        siteId:'',
        orgPriceCost:'',
        carEnterpriseId:'',
      },
      editRules: {
        itemName: [{ required: true, message:"请输入检测项目名称", trigger: 'blur'}],
        carTypeId: [{ required: true, message:"请选择车型", trigger: 'blur'}],
        serialNumber: [{ required: true, message:"请输入序号", trigger: 'blur'}],
        testProductTypeId: [{ required: true, message:"请选择产品类别", trigger: 'blur'}],
        testItemIdListTemp: [{ required: true, message:"请选择检测项目", trigger: 'blur'}],
        orgPriceCost: [{ required: true, message:"请输入对外打包费用", trigger: 'blur'}],
        sitePriceCost: [{ required: true, message:"请输入场地成本费用", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {

      },
      excelImp: {
        dialogVisible: false,
        loading: false,
        fileList:[],
        action: '',
        loadingDiv:'',
        siteId:'',
      },
      carTypeList: [],
      testProductTypeList: [],
      testItemList: [],

      excelImp: {
        dialogVisible: false,
        loading: false,
        fileList:[],
        action: '',
        loadingDiv:'',
        siteId:'',
      },

      baseUrl: '',
      uploadActionUrl: '',
      avatarUploadLoadingDiv: '',

      tabsActiveName: '',
      xctpDialogVisible:false,
      xctpImg:'',
      xctpRow:'',
      siteId:'',

    }
  },
  watch:{

  },
  mounted() {

    let id=this.$route.params.id;

    this.siteId = id;
    this.editForm.siteId=this.siteId;
    // console.log("sId")
    // console.log(this.editForm.sId)



    this.init();
    this.getDataList(this.currentPage);


    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.excelImp.action = this.$adminApiUrl + "test-site-price/excel?userType=0&_t="+t+"&siteId="+this.$route.params.id;
    this.baseUrl = this.$baseUrl;
    this.uploadActionUrl = this.$adminApiUrl + "/uploadToQiNiu?_t="+t;
  },
  methods: {

    parseItem(row){

      let itemList = row.itemList;

      let str = "";
      for(let i in itemList) {
        let item = itemList[i];
        if(item.level == 2) {
          str += item.serialNumber + "/" + item.itemName + "<br>";
        }else if(item.level == 3){
          str += item.serialNumber + "/" + item.parentItemName + "/" + item.itemName + "<br>";
        }
      }

      return str;
    },

    init(){

      // 获取所有车辆类型
      getAllCarTypeList().then(res => {
        if(res.code == 1) {
          this.carTypeList = res.data;
        }
      }).catch(res => {

      });

      // 获取所有检测产品类别
      getAllTestProductTypeList().then(res => {
        if(res.code == 1) {

          this.testProductTypeList = res.data;
        }
      }).catch(res => {

      });

      // 获取检测项目
      getTestItemList().then(res => {
        if(res.code == 1) {
          this.testItemList = res.data;
        }
      }).catch(res => {

      });

      },

    ToFixed(price){
      if(price!=null&&price!=''){
          return parseFloat(price).toFixed(2)
        }else{
          return parseFloat(0).toFixed(2)
        }
    },



    exportExcel(){
      const loadingDiv = util.showLoading("正在导出EXCEL")

      let param = {};
      param['siteId'] = this.$route.params.id;
      // console.log(param);

      let t = getToken();
      let headers = {"x-token": t};
      axios({
        method: 'post',
        url: this.$adminApiUrl + "/test-site-price/excel-export", // 请求地址
        data: param, // 参数
        headers: headers,
        responseType: 'blob' ,// 表明返回服务器返回的数据类型

      }).then(res=>{
        loadingDiv.close();
        let blob = new Blob([res.data], { type: 'application/xlsx' })
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url;
        let timeStr = "";//this.fmtDate(new Date(),"yyyyMMdd_hhmmss");
        link.download = this.siteName+"-"+'场地费维护'+ '.xlsx' // 重命名文件
        link.click()
        URL.revokeObjectURL(url)

      }).catch(err=>{
        console.log(err);
        loadingDiv.close();
        this.$alert("导出失败,请检查网络", {dangerouslyUseHTMLString:true,type:'warning'})
      });
    },



    showAddDialogForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = '';
      }

      this.editForm.testItemIdList = [];
      this.editForm.id = 0
      this.editFormVisible = true;
    },
    handleEdit(index, row) {

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = row[key];
      }

      this.editForm.testProductTypeId = [row.productTypeId1,row.productTypeId2];

      this.editFormVisible = true;

    },



    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {

          // 参数处理
          let param={};
          param['id'] = this.editForm.id;
          param['itemName'] = this.editForm.itemName;
          param['carTypeId'] = this.editForm.carTypeId;
          param['price'] = this.editForm.orgPriceCost;
          param['priceCost'] = this.editForm.sitePriceCost;
          param['serialNumber'] = this.editForm.serialNumber;
          param['note'] = this.editForm.note;
          param['productTypeId1'] = this.editForm.testProductTypeId[0];
          param['productTypeId2'] = this.editForm.testProductTypeId[1];
          param['orgId'] = this.$route.params.id;
          param['sitemItemId'] = this.editForm.sitemItemId;

          // console.log(this.$route.params.id);
          // console.log(param);

          let idList = [];
          let idsList = [];
          for(let i in this.editForm.testItemIdListTemp){
            let x = this.editForm.testItemIdListTemp[i];
            idList.push(x[x.length-1]);
            idsList.push(x.join(","))
          }

          param['testItemIdList'] = idList;
          param['testItemIdsList'] = idsList;

          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateTestOrgPriceCost
          if(this.editForm.id == 0){
            func = addTestItem
          }
          func(param).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.serialNumber+","+row.itemName+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestItem({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },


    handleExcelImp(){

      this.excelImp.fileList=[];
      this.excelImp.dialogVisible = true;
    },
    onUploadSuccess(res, file, fileList){
      this.excelImp.loading = false;
      this.excelImp.loadingDiv.close();

      if(res.code == 0) {
        this.$alert(res.msg,{dangerouslyUseHTMLString:true,type:'warning'})
      }else if(res.code == 1) {
        this.$alert(res.msg,{dangerouslyUseHTMLString:true,type:'success'})
          .then(()=> {
            this.getDataList(1);
            this.excelImp.dialogVisible=false;
          })
      }
    },
    onUploadError(err, file, fileList){
      this.excelImp.loading = false;
      this.excelImp.loadingDiv.close();
      this.$alert("导入失败",{dangerouslyUseHTMLString:true,type:'warning'})
    },
    submitUpload() {
      this.excelImp.loading = true;
      this.excelImp.loadingDiv = util.showLoading("导入中")
      this.$refs.upload.submit();
    },
    handleExcelImp(){

      this.excelImp.fileList=[];
      this.excelImp.dialogVisible = true;
    },




    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getTestOrgPriceCostList({
        pageSize: this.pageSize,
        pageNum: pageNum,
        orgId:this.$route.params.id,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data.records;
          this.currentPage = pageNum;
          this.total = res.data.total;
          this.tableData = data;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })


      // let param = {};
      // param['siteId'] = this.$route.params.id;
      // // console.log(param)
      // getTestSiteList(param).then(res => {
      //   if(res.code == 0) {
      //     this.$message({
      //       showClose: true,
      //       message: res.msg,
      //       type: 'error'
      //     });
      //   }else if(res.code == 1) {
      //     let data = res.data;
      //     this.siteName = data
      //     // console.log(this.siteName)

      //   }
      //   loadingDiv.close();
      // }).catch(res => {
      //   loadingDiv.close();
      // })




      // getTestSitePriceList({
      //   pageSize: this.pageSize,
      //   pageNum: pageNum,
      //   sId:this.$route.params.id

      //   }).then(res => {
      //   if(res.code == 0) {
      //     this.$message({
      //       showClose: true,
      //       message: res.msg,
      //       type: 'error'
      //     });
      //   }else if(res.code == 1) {
      //     let data = res.data;
      //     // this.currentPage = pageNum;
      //     // this.total = res.data.total;
      //     this.tableData1 = data;
      //     console.log("AA");
      //     console.log(this.tableData1);
      //   }
      //   loadingDiv.close();
      // }).catch(res => {
      //   loadingDiv.close();
      // })



      },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
